package com.yanghang.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.InputStream;
import java.util.Properties;

public class JedisUtils {
    private static JedisPool pool;
    static{
        InputStream in = JedisUtils.class.getResourceAsStream("/JedisUtils.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        JedisPoolConfig config = new JedisPoolConfig();
        String maxIdle = p.getProperty("redis.maxIdle");
        if(maxIdle!=null){
            config.setMaxIdle(Integer.parseInt(maxIdle));

        }
        String minIdle = p.getProperty("redis.minIdle");
        if(minIdle!=null){
            config.setMinIdle(Integer.parseInt(minIdle));
        }
        String maxTotal = p.getProperty("redis.maxTotal");
        if(maxTotal!=null){
            config.setMaxTotal(Integer.parseInt(maxTotal));
        }
        String maxWaitMillis = p.getProperty("redis.maxWaitMillis");
        if(maxWaitMillis!=null){
            config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
        }
        String testOnBorrow = p.getProperty("redis.testOnBorrow");
        if(testOnBorrow!=null){
            config.setTestOnBorrow(Boolean.parseBoolean(testOnBorrow));
        }
        String hostName = p.getProperty("redis.hostName");
        String port = p.getProperty("redis.port");
        pool=new JedisPool(config,hostName,Integer.parseInt(port==null?"6379":port));
    }
    public static Jedis getJedis(){
        return pool.getResource();
    }
    public static void close(Jedis jedis){
        if(jedis!=null){
            jedis.close();
        }
    }
}
